//
//  MINUtils.m
//  loginDemo
//
//  Created by lym on 2017/8/19.
//  Copyright © 2017年 lym. All rights reserved.
//

#import "MINUtils.h"
#import "Masonry.h"
#import <sys/utsname.h>
//#import <SAMKeychain/SAMKeychain.h>

#define kMINUtilsMainScreenScaleY [[UIScreen mainScreen]bounds].size.height / 736.0f
#define kMINUtilsMainScreenScaleX [[UIScreen mainScreen]bounds].size.width / 414.0f
#define KMINUtilsMainScreenBounds [[UIScreen mainScreen]bounds]

@implementation MINUtils

+ (UIButton *)createBtnWithTitle:(NSString *)title titleColor:(UIColor *)titleColor backgroundColor:(UIColor *)color cornerRadius:(CGFloat)radius font:(UIFont *)font
{
    UIButton *button = [[UIButton alloc] init];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitle:title forState:UIControlStateHighlighted];
    
    if ([font.fontName isEqualToString:[UIFont systemFontOfSize:font.pointSize].fontName]) {
        button.titleLabel.font = [UIFont fontWithName:@"FiraSans-Medium" size:(font.pointSize)];
    }else if ([font.fontName isEqualToString:[UIFont boldSystemFontOfSize:font.pointSize].fontName]) {
        button.titleLabel.font = [UIFont fontWithName:@"FiraSans-Bold" size:(font.pointSize)];
    }else {
        button.titleLabel.font = font;
    }
//    button.titleLabel.font = font;
//    button.titleLabel.textColor = titleColor;
    [button setTitleColor:titleColor forState:UIControlStateNormal];
    button.backgroundColor = color;
    
    if (radius > 0) {
        button.layer.cornerRadius = radius;
        button.layer.masksToBounds = YES;
    }
    
    return button;
}

+ (UITextField *)createTextFieldWithPlacehold:(NSString *)holdText font:(UIFont *)font textColor:(UIColor *)color
{
    UITextField *textField = [[UITextField alloc] init];
    if ([font.fontName isEqualToString:[UIFont systemFontOfSize:font.pointSize].fontName]) {
        textField.font = [UIFont fontWithName:@"FiraSans-Medium" size:(font.pointSize)];
    }else if ([font.fontName isEqualToString:[UIFont boldSystemFontOfSize:font.pointSize].fontName]) {
        textField.font = [UIFont fontWithName:@"FiraSans-Bold" size:(font.pointSize)];
    }else {
        textField.font = font;
    }
//    textField.font = font;
    NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc] initWithString:holdText];
    [placeholder addAttribute:NSFontAttributeName value: textField.font range:NSMakeRange(0, holdText.length)];
    [placeholder addAttribute:NSForegroundColorAttributeName value: color range:NSMakeRange(0, holdText.length)];
    NSMutableParagraphStyle *centerStyle = [textField.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
    centerStyle.minimumLineHeight = textField.font.lineHeight - (textField.font.lineHeight - textField.font.lineHeight) / 2.0;
    [placeholder addAttribute:NSParagraphStyleAttributeName value:centerStyle range:NSMakeRange(0, holdText.length)];
    textField.attributedPlaceholder = placeholder;
    textField.textColor = color;
    textField.tintColor = color;
//    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    return textField;
}


+ (UILabel *)createLabelWithText:(NSString *)text font:(UIFont *)font textColor:(UIColor *)textColor
{
    UILabel *label = [[UILabel alloc] init];
    label.text = text;
    
    if ([font.fontName isEqualToString:[UIFont systemFontOfSize:font.pointSize].fontName]) {
        label.font = [UIFont fontWithName:@"FiraSans-Medium" size:(font.pointSize)];
    }else if ([font.fontName isEqualToString:[UIFont boldSystemFontOfSize:font.pointSize].fontName]) {
        label.font = [UIFont fontWithName:@"FiraSans-Bold" size:(font.pointSize)];
    }else {
        label.font = font;
    }
    label.textColor = textColor;
    return label;
}

+ (UIView *)createViewWithRadius:(CGFloat)radius
{
    UIView *view = [[UIView alloc] init];
    view.layer.cornerRadius = radius;
    view.layer.masksToBounds = YES;
    return view;
}


+ (UITextView *)createTextViewWithPlaceholder:(NSString *)text font:(UIFont *)font backgroundColor:(UIColor *)color cornerRadius:(CGFloat)radius textColor:(UIColor *)textColor
{
    UITextView *textView = [[UITextView alloc] init];
    textView.backgroundColor = color;
    textView.layer.cornerRadius = radius;
    textView.layer.masksToBounds = YES;
    textView.font = font;
    textView.textColor = textColor;
    // _placeholderLabel
    UILabel *placeHolderLabel = [self createLabelWithText:text font:[UIFont systemFontOfSize:12] textColor:textColor];
    placeHolderLabel.font = font;
    placeHolderLabel.numberOfLines = 0;
    [placeHolderLabel sizeToFit];
    [textView addSubview:placeHolderLabel];
    [textView setValue:placeHolderLabel forKey:@"_placeholderLabel"];
    return textView;
}

+ (NSMutableAttributedString *)getTextAttributeStringWithPlaceHold:(NSString *)holdText
{
    UITextField *textField = [[UITextField alloc] init];
    textField.font = [UIFont fontWithName:@"FiraSans-Regular" size:12];
    NSMutableAttributedString *placeholder = [[NSMutableAttributedString alloc] initWithString:holdText];
    [placeholder addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"FiraSans-Regular" size:12] range:NSMakeRange(0, holdText.length)];
    [placeholder addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:167.0 / 255 green:207.0 / 255 blue:250.0 / 255 alpha:1.0] range:NSMakeRange(0, holdText.length)];
    NSMutableParagraphStyle *centerStyle = [textField.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
    centerStyle.minimumLineHeight = textField.font.lineHeight - (textField.font.lineHeight - [UIFont systemFontOfSize:12.0].lineHeight) / 2.0;
    [placeholder addAttribute:NSParagraphStyleAttributeName value:centerStyle range:NSMakeRange(0, holdText.length)];
    return placeholder;
}

+ (NSString *)getSystemTimeTimestamp:(NSString *)timestamp {
    
    NSString *gmtStr;
//    if ([UserLoginModelManager shareManager].systemConfiguationModel.time_zone.length > 0) {
//        gmtStr = [UserLoginModelManager shareManager].systemConfiguationModel.time_zone;
//    }else {
        NSTimeZone *zone = [NSTimeZone systemTimeZone];
        NSString *zoneAbbreviation = [zone abbreviation];
        gmtStr = zoneAbbreviation;
//    }
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MMM dd,yyyy HH:mm:ss"];
    
    NSString *language = [[NSUserDefaults standardUserDefaults]objectForKey:@"userLanguage"];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier: language];
    [formatter setLocale:locale];
    
    NSTimeZone *timeZone;
    if ([gmtStr containsString:@"GMT"] || [gmtStr containsString:@"gmt"]) {
        if (gmtStr.length >= 8) {
            NSString *gmtNum = [NSString stringWithFormat:@"%@%@",[gmtStr substringWithRange:NSMakeRange(3, 1)],[gmtStr substringWithRange:NSMakeRange(4, 2)]];
            
            NSString *gmtNum02 = [NSString stringWithFormat:@"%@%@",[gmtStr substringWithRange:NSMakeRange(3, 1)],[gmtStr substringWithRange:NSMakeRange(gmtStr.length-2, 2)]];
            
            timeZone = [NSTimeZone timeZoneForSecondsFromGMT:(gmtNum.integerValue*60*60 + gmtNum02.integerValue*60)];
        }else{
            NSString *gmtNum = [gmtStr substringWithRange:NSMakeRange(3, gmtStr.length-3)];
            timeZone = [NSTimeZone timeZoneForSecondsFromGMT:(gmtNum.integerValue*60*60)];
        }
    }else {
        timeZone = [NSTimeZone timeZoneWithAbbreviation:gmtStr];
    }
    [formatter setTimeZone:timeZone];
    
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue] / 1000];
    NSString *dateString = [formatter stringFromDate:date];///[NSString stringWithFormat:@"%@(%@)",[formatter stringFromDate:date],gmtStr];
    return dateString;
}

+ (NSString *)getSystemTimeTimestamp:(NSString *)timestamp formatter:(NSString *)formatterString {
    
    NSString *gmtStr;
//    if ([UserLoginModelManager shareManager].systemConfiguationModel.time_zone.length > 0) {
//        gmtStr = [UserLoginModelManager shareManager].systemConfiguationModel.time_zone;
//    }else {
        NSTimeZone *zone = [NSTimeZone systemTimeZone];
        NSString *zoneAbbreviation = [zone abbreviation];
        gmtStr = zoneAbbreviation;
//    }
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:formatterString];
    
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:[BRLanguageManager share].language];
//    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier: language];
    [formatter setLocale:locale];
    
    NSTimeZone *timeZone;
    if ([gmtStr containsString:@"GMT"] || [gmtStr containsString:@"gmt"]) {
        if (gmtStr.length >= 8) {
            NSString *gmtNum = [NSString stringWithFormat:@"%@%@",[gmtStr substringWithRange:NSMakeRange(3, 1)],[gmtStr substringWithRange:NSMakeRange(4, 2)]];
            
            NSString *gmtNum02 = [NSString stringWithFormat:@"%@%@",[gmtStr substringWithRange:NSMakeRange(3, 1)],[gmtStr substringWithRange:NSMakeRange(gmtStr.length-2, 2)]];
            
            timeZone = [NSTimeZone timeZoneForSecondsFromGMT:(gmtNum.integerValue*60*60 + gmtNum02.integerValue*60)];
        }else{
            NSString *gmtNum = [gmtStr substringWithRange:NSMakeRange(3, gmtStr.length-3)];
            timeZone = [NSTimeZone timeZoneForSecondsFromGMT:(gmtNum.integerValue*60*60)];
        }
    }else {
        timeZone = [NSTimeZone timeZoneWithAbbreviation:gmtStr];
    }
    [formatter setTimeZone:timeZone];
    
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue] / 1000];
    
    NSString *dateString;
//    if (formatterString.length == @"MMM dd yyyy".length) {
        dateString = [NSString stringWithFormat:@"%@",[formatter stringFromDate:date]];
//    }else {
//        dateString = [NSString stringWithFormat:@"%@(%@)",[formatter stringFromDate:date],gmtStr];
//    }
    return dateString;
}

+ (NSString *)getUsingTimeByCurrTime:(NSString *)usedTime
{
    NSString *returnStr;
    NSInteger temp = [usedTime integerValue];
    if (temp < 1) {
        return returnStr = Localized(@"PUBLIC_LESSMIN");
    }else if (temp < 60) {
        return returnStr = Localized(@"PUBLIC_LESSMIN");
    }else if (temp < 3600) {
        NSInteger min = temp / 60;
        return returnStr = [NSString stringWithFormat:@"%ld %@", (long)min, Localized(@"PUBLIC_MIN")];
    }else {

        NSInteger hour = temp / 3600;
        NSInteger min = temp % 3600 / 60;
        return returnStr = [NSString stringWithFormat:@"%ld %@ %ld %@", (long)hour, Localized(@"PUBLIC_HOUR"), (long)min, Localized(@"PUBLIC_MIN")];
    }

    return @"--";
}

+ (NSString *)getUsingTimeByUsed:(NSString *)usedTime
{
    NSString *returnStr;
    NSInteger temp = [usedTime integerValue];
    if (temp < 1) {
        returnStr = Localized(@"PUBLIC_LESSMIN");
    }
    else if (temp >= 1 && temp < 60) {
        returnStr = [NSString stringWithFormat:@"%@ %@", usedTime, Localized(@"PUBLIC_MIN")];
    }else{
        NSInteger hour = temp / 60;
        NSInteger min = temp % 60;
        returnStr = [NSString stringWithFormat:@"%ld %@ %ld %@", (long)hour, Localized(@"PUBLIC_HOUR"), (long)min, Localized(@"PUBLIC_MIN")];
    }
    return returnStr;
}

+ (NSString *)getCustomTime:(NSString *)gmtStr Timestamp:(NSString *)timestamp {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MMM dd,yyyy HH:mm:ss"];
    
    NSString *language = [[NSUserDefaults standardUserDefaults]objectForKey:@"userLanguage"];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier: language];
    [formatter setLocale:locale];
    
    NSTimeZone *timeZone;
    if ([gmtStr containsString:@"GMT"] || [gmtStr containsString:@"gmt"]) {
        if (gmtStr.length >= 8) {
            NSString *gmtNum = [NSString stringWithFormat:@"%@%@",[gmtStr substringWithRange:NSMakeRange(3, 1)],[gmtStr substringWithRange:NSMakeRange(4, 2)]];
            
            NSString *gmtNum02 = [NSString stringWithFormat:@"%@%@",[gmtStr substringWithRange:NSMakeRange(3, 1)],[gmtStr substringWithRange:NSMakeRange(gmtStr.length-2, 2)]];
            
            timeZone = [NSTimeZone timeZoneForSecondsFromGMT:(gmtNum.integerValue*60*60 + gmtNum02.integerValue*60)];
        }else{
            NSString *gmtNum = [gmtStr substringWithRange:NSMakeRange(3, gmtStr.length-3)];
            timeZone = [NSTimeZone timeZoneForSecondsFromGMT:(gmtNum.integerValue*60*60)];
        }
    }else {
        timeZone = [NSTimeZone timeZoneWithAbbreviation:gmtStr];
    }
    [formatter setTimeZone:timeZone];
    
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue] / 1000];
    NSString *dateString = [NSString stringWithFormat:@"%@(%@)",[formatter stringFromDate:date],gmtStr];
    return dateString;
}

+ (NSString *)getCustomTime:(NSString *)gmtStr Timestamp:(NSString *)timestamp formatter:(NSString *)formatterString {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:formatterString];
    
    NSString *language = [[NSUserDefaults standardUserDefaults]objectForKey:@"userLanguage"];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier: language];
    [formatter setLocale:locale];
    
    NSTimeZone *timeZone;
    if ([gmtStr containsString:@"GMT"] || [gmtStr containsString:@"gmt"]) {
        if (gmtStr.length >= 8) {
            NSString *gmtNum = [NSString stringWithFormat:@"%@%@",[gmtStr substringWithRange:NSMakeRange(3, 1)],[gmtStr substringWithRange:NSMakeRange(4, 2)]];
            
            NSString *gmtNum02 = [NSString stringWithFormat:@"%@%@",[gmtStr substringWithRange:NSMakeRange(3, 1)],[gmtStr substringWithRange:NSMakeRange(gmtStr.length-2, 2)]];
            
            timeZone = [NSTimeZone timeZoneForSecondsFromGMT:(gmtNum.integerValue*60*60 + gmtNum02.integerValue*60)];
        }else{
            NSString *gmtNum = [gmtStr substringWithRange:NSMakeRange(3, gmtStr.length-3)];
            timeZone = [NSTimeZone timeZoneForSecondsFromGMT:(gmtNum.integerValue*60*60)];
        }
    }else {
        timeZone = [NSTimeZone timeZoneWithAbbreviation:gmtStr];
    }

    [formatter setTimeZone:timeZone];
    
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue] / 1000];
    NSString *dateString = [NSString stringWithFormat:@"%@(%@)",[formatter stringFromDate:date],gmtStr];
    return dateString;
}

+ (NSString *)getTimeFromTimestamp:(NSString *)timestamp formatter:(NSString *)formatterString
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat: formatterString];
//    NSString *language = [[NSUserDefaults standardUserDefaults]objectForKey:@"userLanguage"];
//    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier: language];
//    [formatter setLocale:locale];
    
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue] / 1000];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}

+ (NSString *)getTimeFromTimestamp:(NSString *)timestamp formatter:(NSString *)formatterString usedTime:(int)usedTime
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat: formatterString];
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue] / 1000];
    date =  [date dateByAddingTimeInterval: usedTime * 60];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}

// 和当前时间对比
+ (NSString *)getDuringTimeFromTimestamp:(NSString *)timestamp {
    
    NSDate *lastDate = [NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue] / 1000];
    NSDate *currentDate = [NSDate date];
    double interval = [currentDate timeIntervalSinceDate: lastDate];
    NSLog(@"%lf", interval);
   // NSLog(@"last = %@, now = %@", [formatter stringFromDate: lastDate], [formatter stringFromDate: currentDate]);
    // 当前日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 需要对比的时间数据
    NSCalendarUnit unit = /*NSCalendarUnitYear | NSCalendarUnitMonth
                           | NSCalendarUnitDay |*/  NSCalendarUnitHour | NSCalendarUnitMinute| NSCalendarUnitSecond;
    // 对比时间差
    NSDateComponents *dateCom = [calendar components:unit fromDate:lastDate toDate:currentDate options:0];
    //NSLog(@"year = %ld, month = %ld, day = %ld, hour = %ld, min = %ld, sec = %ld", dateCom.year, dateCom.month, dateCom.day, dateCom.hour, dateCom.minute, (long)dateCom.second);
    return [NSString stringWithFormat: @"%02ld:%02ld:%02ld", (long)dateCom.hour, (long)dateCom.minute, (long)dateCom.second];
}

// 和当前时间对比
+ (NSString *)getContrastTimeFromTimestamp:(NSString *)timestamp {
    
    NSDate *lastDate = [NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue] / 1000];
    NSDate *currentDate = [NSDate date];
    double interval = [currentDate timeIntervalSinceDate: lastDate];
    NSLog(@"%lf", interval);
    
    
    
    // NSLog(@"last = %@, now = %@", [formatter stringFromDate: lastDate], [formatter stringFromDate: currentDate]);
    // 当前日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 需要对比的时间数据
    NSCalendarUnit unit = /*NSCalendarUnitYear | NSCalendarUnitMonth
                           | NSCalendarUnitDay |*/  NSCalendarUnitHour | NSCalendarUnitMinute| NSCalendarUnitSecond;
    // 对比时间差
    NSDateComponents *dateCom = [calendar components:unit fromDate:lastDate toDate:currentDate options:0];
    //NSLog(@"year = %ld, month = %ld, day = %ld, hour = %ld, min = %ld, sec = %ld", dateCom.year, dateCom.month, dateCom.day, dateCom.hour, dateCom.minute, (long)dateCom.second);
    return [NSString stringWithFormat: @"%02ld:%02ld:%02ld", (long)dateCom.hour, (long)dateCom.minute, (long)dateCom.second];
}

+ (NSURL *)getHeadUrl:(NSString *)head
{
    if ([head rangeOfString:@"http"].location != NSNotFound) {
        return [NSURL URLWithString: head];
    }
//    return  [NSURL URLWithString: [NSString stringWithFormat: @"%@%@", BASE_URL, head]];
    return  [NSURL URLWithString: [NSString stringWithFormat: @"%@", head]];
}

//比较两个日期大小
- (NSInteger)compare:(NSDate *)startTime to:(NSDate *)endTime {
    
    // 当前日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 需要对比的时间数据
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth
    | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    // 对比时间差
    NSDateComponents *dateCom = [calendar components:unit fromDate:startTime toDate:endTime options:0];
    NSString *time = [NSString stringWithFormat:@"%ld%ld%ld%ld%ld%ld",dateCom.year,dateCom.month,dateCom.day,dateCom.hour,dateCom.minute,dateCom.second];
    NSLog(@"time---->%@",time);
    
    return [time integerValue];
}

//获取字符串高 // 传一个字符串和字体大小来返回一个字符串所占的高度
+ (float)measureMutilineStringHeight:(NSString*)str andFont:(UIFont*)wordFont andWidthSetup:(float)width {
    
    if (str == nil || width <= 0) return 0;
    
    CGSize measureSize;
    
    if([[UIDevice currentDevice].systemVersion floatValue] < 7.0){
        
        measureSize = [str sizeWithFont:wordFont constrainedToSize:CGSizeMake(width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
        
    }else{
        
        measureSize = [str boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:wordFont, NSFontAttributeName, nil] context:nil].size;
        
    }
    
    return ceil(measureSize.height);
    
}

// 传一个字符串和字体大小来返回一个字符串所占的宽度
+(float)measureSinglelineStringWidth:(NSString*)str andFont:(UIFont*)wordFont {
    
    if (str == nil) return 0;
    
    CGSize measureSize;
    
    if([[UIDevice currentDevice].systemVersion floatValue] < 7.0){
        
        measureSize = [str sizeWithFont:wordFont constrainedToSize:CGSizeMake(MAXFLOAT, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
        
    }else{
        
        measureSize = [str boundingRectWithSize:CGSizeMake(0, 0) options:NSStringDrawingUsesFontLeading attributes:[NSDictionary dictionaryWithObjectsAndKeys:wordFont, NSFontAttributeName, nil] context:nil].size;
        
    }
    
    return ceil(measureSize.width);
    
}

+(CGSize)measureSinglelineStringSize:(NSString*)str andFont:(UIFont*)wordFont {
    
    if (str == nil) return CGSizeZero;
    
    CGSize measureSize;
    
    if([[UIDevice currentDevice].systemVersion floatValue] < 7.0){
        
        measureSize = [str sizeWithFont:wordFont constrainedToSize:CGSizeMake(MAXFLOAT, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
        
    }else{
        
        measureSize = [str boundingRectWithSize:CGSizeMake(0, 0) options:NSStringDrawingUsesFontLeading attributes:[NSDictionary dictionaryWithObjectsAndKeys:wordFont, NSFontAttributeName, nil] context:nil].size;
        
    }
    
    return measureSize;
}

//正则判断
+ (BOOL)checkEmail:(NSString *)email {
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

//正则判断
/**
 粘贴板获取邀请码正则：
 \[battbox-[\w]+\]

 栗子：
 [battbox-123456]
 */
+ (BOOL)checkInvCode:(NSString *)code {
    
    NSString *codeRegex = @"\\[battbox-\\w+\\]";
    NSPredicate *codeTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", codeRegex];
    return [codeTest evaluateWithObject:code];
}

//处理中文
+ (NSString *)strUTF8Encoding:(NSString *)str {
    return [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            }

//获取系统时区
+ (NSString *)getCusZoneString {
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSString *cusZone;
    NSInteger secondsGMT = [zone secondsFromGMT];
    
    if (secondsGMT<0) {
        NSInteger teamGMT = secondsGMT*(-1);
        NSInteger hour = teamGMT/3600;
        NSInteger min = teamGMT/60%60;
        
        if (min == 0) {
            cusZone = [NSString stringWithFormat:@"GMT-%02ld",hour];
        }else {
            cusZone = [NSString stringWithFormat:@"GMT-%02ld:%02ld",hour,min];
        }
    }else {
        NSInteger hour = secondsGMT/3600;
        NSInteger min = secondsGMT/60%60;
        
        if (min == 0) {
            cusZone = [NSString stringWithFormat:@"GMT+%02ld",hour];
        }else {
            cusZone = [NSString stringWithFormat:@"GMT+%02ld:%02ld",hour,min];
        }
    }
    return cusZone;
}

// 获取 Bundle num
+ (NSString *)getBundleNum {
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
}

// 获取手机型号
+ (NSString *)getIphoneType {
    //需要导入头文件：#import <sys/utsname.h>
    struct utsname systemInfo;
    uname(&systemInfo);
    
    NSString *platform = [NSString stringWithCString: systemInfo.machine encoding:NSASCIIStringEncoding];
    
    //iPhone
    if([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
    
    if([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    
    if([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
    
    if([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    
    if([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
    
    if([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
    
    if([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    
    if([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    
    if([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
    
    if([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";
    
    if([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
    
    if([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";
    
    if([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
    
    if([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
    
    if([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    
    if([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    
    if([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    
    if([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
    
    if([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7";
    
    if([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";
    
    if([platform isEqualToString:@"iPhone9,3"]) return @"iPhone 7";
    
    if([platform isEqualToString:@"iPhone9,4"]) return @"iPhone 7 Plus";
    
    if([platform isEqualToString:@"iPhone10,1"])return @"iPhone 8";
    
    if([platform isEqualToString:@"iPhone10,4"])return @"iPhone 8";
    
    if([platform isEqualToString:@"iPhone10,2"])return @"iPhone 8 Plus";
    
    if([platform isEqualToString:@"iPhone10,5"])return @"iPhone 8 Plus";
    
    if([platform isEqualToString:@"iPhone10,3"])return @"iPhone X";
    
    if([platform isEqualToString:@"iPhone10,6"])return @"iPhone X";
    
    if([platform isEqualToString:@"iPhone11,2"])return @"iPhone XS";
    
    if([platform isEqualToString:@"iPhone11,4"])return @"iPhone XS Max";
    
    if([platform isEqualToString:@"iPhone11,6"])return @"iPhone XS Max";
    
    if([platform isEqualToString:@"iPhone11,8"])return @"iPhone XR";
    
    if([platform isEqualToString:@"iPhone12,1"])return @"iPhone 11";
    
    if([platform isEqualToString:@"iPhone12,3"])return @"iPhone 11 Pro";
    
    if([platform isEqualToString:@"iPhone12,5"])return @"iPhone 11 Pro Max";
    
    if([platform isEqualToString:@"iPhone12,8"]) return @"iPhone SE 2";
    if([platform isEqualToString:@"iPhone13,1"]) return @"iPhone 12 mini";
    if([platform isEqualToString:@"iPhone13,2"]) return @"iPhone 12";
    if([platform isEqualToString:@"iPhone13,3"]) return @"iPhone 12 Pro";
    if([platform isEqualToString:@"iPhone14,2"]) return @"iPhone 13 Pro";
    if([platform isEqualToString:@"iPhone14,3"]) return @"iPhone 13 Pro Max";
    if([platform isEqualToString:@"iPhone14,4"]) return @"iPhone 13 mini";
    if([platform isEqualToString:@"iPhone14,5"]) return @"iPhone 13";
    if([platform isEqualToString:@"iPhone14,6"]) return @"iPhone SE 3";
    if([platform isEqualToString:@"iPhone14,7"]) return @"iPhone 14";
    if([platform isEqualToString:@"iPhone14,8"]) return @"iPhone 14 Plus";
    if([platform isEqualToString:@"iPhone15,2"]) return @"iPhone 14 Pro";
    if([platform isEqualToString:@"iPhone15,3"]) return @"iPhone 14 Pro Max";
    if ([platform isEqualToString:@"iPhone15,4"]) return @"iPhone 15";
    if ([platform isEqualToString:@"iPhone15,5"]) return @"iPhone 15 Plus";
    if ([platform isEqualToString:@"iPhone16,1"]) return @"iPhone 15 Pro";
    if ([platform isEqualToString:@"iPhone16,2"]) return @"iPhone 15 Pro Max";
    if ([platform isEqualToString:@"iPhone17,3"]) return @"iPhone 16";
    if ([platform isEqualToString:@"iPhone17,4"]) return @"iPhone 16 Plus";
    if ([platform isEqualToString:@"iPhone17,1"]) return @"iPhone 16 Pro";
    if ([platform isEqualToString:@"iPhone17,2"]) return @"iPhone 16 Pro Max";
    
    //iPod
    if([platform isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G";
    
    if([platform isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G";
    
    if([platform isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G";
    
    if([platform isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G";
    
    if([platform isEqualToString:@"iPod5,1"]) return @"iPod Touch 5G";
    
    
    //iPad
    if([platform isEqualToString:@"iPad1,1"]) return @"iPad 1G";
    
    if([platform isEqualToString:@"iPad2,1"]) return @"iPad 2";
    
    if([platform isEqualToString:@"iPad2,2"]) return @"iPad 2";
    
    if([platform isEqualToString:@"iPad2,3"]) return @"iPad 2";
    
    if([platform isEqualToString:@"iPad2,4"]) return @"iPad 2";
    
    if([platform isEqualToString:@"iPad2,5"]) return @"iPad Mini 1G";
    
    if([platform isEqualToString:@"iPad2,6"]) return @"iPad Mini 1G";
    
    if([platform isEqualToString:@"iPad2,7"]) return @"iPad Mini 1G";
    
    if([platform isEqualToString:@"iPad3,1"]) return @"iPad 3";
    
    if([platform isEqualToString:@"iPad3,2"]) return @"iPad 3";
    
    if([platform isEqualToString:@"iPad3,3"]) return @"iPad 3";
    
    if([platform isEqualToString:@"iPad3,4"]) return @"iPad 4";
    
    if([platform isEqualToString:@"iPad3,5"]) return @"iPad 4";
    
    if([platform isEqualToString:@"iPad3,6"]) return @"iPad 4";
    
    if([platform isEqualToString:@"iPad4,1"]) return @"iPad Air";
    
    if([platform isEqualToString:@"iPad4,2"]) return @"iPad Air";
    
    if([platform isEqualToString:@"iPad4,3"]) return @"iPad Air";
    
    if([platform isEqualToString:@"iPad4,4"]) return @"iPad Mini 2G";
    
    if([platform isEqualToString:@"iPad4,5"]) return @"iPad Mini 2G";
    
    if([platform isEqualToString:@"iPad4,6"]) return @"iPad Mini 2G";
    
    if([platform isEqualToString:@"iPad4,7"]) return @"iPad Mini 3";
    
    if([platform isEqualToString:@"iPad4,8"]) return @"iPad Mini 3";
    
    if([platform isEqualToString:@"iPad4,9"]) return @"iPad Mini 3";
    
    if([platform isEqualToString:@"iPad5,1"]) return @"iPad Mini 4";
    
    if([platform isEqualToString:@"iPad5,2"]) return @"iPad Mini 4";
    
    if([platform isEqualToString:@"iPad5,3"]) return @"iPad Air 2";
    
    if([platform isEqualToString:@"iPad5,4"]) return @"iPad Air 2";
    
    if([platform isEqualToString:@"iPad6,3"]) return @"iPad Pro 9.7";
    
    if([platform isEqualToString:@"iPad6,4"]) return @"iPad Pro 9.7";
    
    if([platform isEqualToString:@"iPad6,7"]) return @"iPad Pro 12.9";
    
    if([platform isEqualToString:@"iPad6,8"]) return @"iPad Pro 12.9";
    
    
    //iPhone Simulator
    if([platform isEqualToString:@"i386"]) return @"iPhone Simulator";
    
    if([platform isEqualToString:@"x86_64"]) return @"iPhone Simulator";
    
    return platform;
}


#pragma mark - FindCurrentShowingViewController
/* 完整的描述请参见文件头部 */
+ (UIViewController *)findCurrentShowingViewController {
    //获得当前活动窗口的根视图
    UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *currentShowingVC = [self findCurrentShowingViewControllerFrom:vc];
    return currentShowingVC;
}

//注意考虑几种特殊情况：①A present B, B present C，参数vc为A时候的情况
/* 完整的描述请参见文件头部 */
+ (UIViewController *)findCurrentShowingViewControllerFrom:(UIViewController *)vc
{
    //方法1：递归方法 Recursive method
    UIViewController *currentShowingVC;
    if ([vc presentedViewController]) { //注要优先判断vc是否有弹出其他视图，如有则当前显示的视图肯定是在那上面
        // 当前视图是被presented出来的
        UIViewController *nextRootVC = [vc presentedViewController];
        currentShowingVC = [self findCurrentShowingViewControllerFrom:nextRootVC];
        
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController
        UIViewController *nextRootVC = [(UITabBarController *)vc selectedViewController];
        currentShowingVC = [self findCurrentShowingViewControllerFrom:nextRootVC];
        
    } else if ([vc isKindOfClass:[UINavigationController class]]){
        // 根视图为UINavigationController
        UIViewController *nextRootVC = [(UINavigationController *)vc visibleViewController];
        currentShowingVC = [self findCurrentShowingViewControllerFrom:nextRootVC];
        
    }  else {
        // 根视图为非导航类
        currentShowingVC = vc;
    }
    
    return currentShowingVC;
}

#pragma mark - FindBelongViewControllerForView
+ (nullable UIViewController *)findBelongViewControllerForView:(UIView *)view {
    UIResponder *responder = view;
    while ((responder = [responder nextResponder])) {
        if ([responder isKindOfClass: [UIViewController class]]) {
            return (UIViewController *)responder;
        }
    }
    return nil;
}

#pragma mark - 解析网页地址
/**
 *  截取URL中的参数
 *
 *  @return NSMutableDictionary parameters
 */
+ (NSMutableDictionary *)getURLParameters:(NSString *)url {
    
    // 查找参数
    NSRange range = [url rangeOfString:@"?"];
    if (range.location == NSNotFound) {
        return nil;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    // 截取参数
    NSString *parametersString = [url substringFromIndex:range.location + 1];
    
    // 判断参数是单个参数还是多个参数
    if ([parametersString containsString:@"&"]) {
        
        // 多个参数，分割参数
        NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
        
        for (NSString *keyValuePair in urlComponents) {
            // 生成Key/Value
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
            
            // Key不能为nil
            if (key == nil || value == nil) {
                continue;
            }
            
            id existValue = [params valueForKey:key];
            
            if (existValue != nil) {
                
                // 已存在的值，生成数组
                if ([existValue isKindOfClass:[NSArray class]]) {
                    // 已存在的值生成数组
                    NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
                    [items addObject:value];
                    
                    [params setValue:items forKey:key];
                } else {
                    
                    // 非数组
                    [params setValue:@[existValue, value] forKey:key];
                }
                
            } else {
                
                // 设置值
                [params setValue:value forKey:key];
            }
        }
    } else {
        // 单个参数
        
        // 生成Key/Value
        NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];
        
        // 只有一个参数，没有值
        if (pairComponents.count == 1) {
            return nil;
        }
        
        // 分隔值
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        
        // Key不能为nil
        if (key == nil || value == nil) {
            return nil;
        }
        
        // 设置值
        [params setValue:value forKey:key];
    }
    
    return params;
}

+(NSMutableAttributedString *) getTitleAttributedString:(NSString *)title
{
    NSMutableAttributedString *atStr = [[NSMutableAttributedString alloc]
                                        initWithString:@"* "
                                        attributes:@{
                                                     NSForegroundColorAttributeName : [UIColor orangeColor],
                                                     NSFontAttributeName:[UIFont systemFontOfSize:15]
                                                     }];
    [atStr appendAttributedString:[[NSAttributedString alloc]
                                   initWithString:title
                                   attributes:@{
                                                NSForegroundColorAttributeName : [UIColor orangeColor],
                                                NSFontAttributeName:[UIFont systemFontOfSize:15]
                                                }]];
    return atStr;
}

+(NSMutableAttributedString *) getTitleAttributedStringTwo:(NSString *)title
{
    NSMutableAttributedString *atStr = [[NSMutableAttributedString alloc]
                                        initWithString:@"* "
                                        attributes:@{
                                                     NSForegroundColorAttributeName : [UIColor orangeColor],
                                                     NSFontAttributeName:[UIFont systemFontOfSize:12]
                                                     }];
    [atStr appendAttributedString:[[NSAttributedString alloc]
                                   initWithString:title
                                   attributes:@{
                                                NSForegroundColorAttributeName : [UIColor orangeColor],
                                                NSFontAttributeName:[UIFont systemFontOfSize:12]
                                                }]];
    return atStr;
}

+ (NSString *)nullToString:(id)string {
    
    if ([string isEqual:@"NULL"] || [string isKindOfClass:[NSNull class]] || [string isEqual:[NSNull null]] || [string isEqual:NULL] || [[string class] isSubclassOfClass:[NSNull class]] || string == nil || string == NULL || [string isKindOfClass:[NSNull class]] || [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0 || [string isEqualToString:@"<null>"] || [string isEqualToString:@"(null)"]) {
        return @"";
    } else {
        return (NSString *)string;
    }
}

//H5国际化
+ (NSString *)languagetypeAgreement:(id)agreementUrl
{
    //语言
    NSString *headerLanguage;
    NSString *language = [[NSUserDefaults standardUserDefaults]objectForKey:@"userLanguage"];
    if ([language containsString:@"zh"]) {
        headerLanguage = @"zh-Hans";
    }else {
        headerLanguage = language;
    }
    /*
     zh-Hans
     en
     it
     */
    NSString *agreementRes = [NSString stringWithFormat: @"%@?languagetype=%@",agreementUrl,headerLanguage];
    
    return agreementRes;
}

@end
